今天講註冊
有不一樣的地方
userAuth/urls.py
...
path('register/', views.register, name='register')
...
user.set_password(user.password)
一定要寫這個因為 password 要call func 做加密
userAuth/views.py
...
def register(request):
if request.method == 'GET':
registerForm = RegisterForm()
return render(request, 'userAuth/register.html', {'registerForm':registerForm})
elif request.method == 'POST':
registerForm = RegisterForm(request.POST)
if not registerForm.is_valid():
return render(request, 'userAuth/register.html', {'registerForm':registerForm})
user = registerForm.save()
user.set_password(user.password)
user.save()
messages.error(request, '註冊成功')
return redirect(reverse('main:main'))
...
客製化驗證欄位 def clean_<field>(self)
可以寫一個驗證密碼與確認密碼,就不用在views.py 寫
參考
https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/
user Model 欄位
https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/
userAuth/forms.py
from django import forms
from django.contrib.auth.models import User
class RegisterForm(forms.ModelForm):
username = forms.CharField(label='帳號')
email = forms.EmailField(label='信箱')
password = forms.CharField(label='密碼', widget=forms.PasswordInput())
password2 = forms.CharField(label='確認密碼', widget=forms.PasswordInput())
def clean_password2(self):
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password != password2:
raise forms.ValidationError('密碼和確認密碼不同')
return password2
class Meta:
model = User
fields = ('username', 'email', 'password', 'password2')
userAuth/templates/userAuth/register.html
{% extends 'main/base.html' %}
{% block content %}
<h2>註冊</h2>
<form method="post" action="{% url 'userAuth:register' %}">
{% csrf_token %}
{{ registerForm.as_p }}
<input type="submit" value="註冊">
</form>
{% endblock %}
就完成了